package com.rxy.api;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class GetNoteData implements Watcher {

    // 计数工具类，让线程处于等待阻塞，主要不让main方法结束
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws Exception {
        // 客户端可以通过创建一个zk实例来连接zk服务器
        zooKeeper = new ZooKeeper("192.168.31.247:2181",
                5000, new GetNoteData());
        // 让会话一直保持着
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        // 子节点列表发生变化时，服务器会发出NodeChildrenChanged事件通知，但不会把变化情况告诉给客户端
        // 需要客户端自行获取，且通知是一次性的，需反复注册监听
        if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
            try {
                List<String> children = zooKeeper.getChildren(watchedEvent.getPath(), true);
                System.out.println("子节点列表更新："+children);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 当连接创建了，服务端发送给客户端SyncConnected事件
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            try {
                // 调用获取单个节点数据方法
                getNoteDate();
                // 调用获取单个节点子节点列表方法
                getChildrens();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取某个节点的数据
     */
    private void getNoteDate() throws Exception {
        /**
         * zooKeeper.getData(path, watch, stat);
         * path：获取数据的路径
         * watch：是否开启监听
         * stat：节点状态信息（null：表示获取最新版本的数据）
         */
        byte[] data = zooKeeper.getData("/rxy-persistent", false, null);
        System.out.println(new String(data, "utf-8"));
    }

    /**
     * 获取某个节点的子节点列表
     */
    private void getChildrens() throws Exception {
        /**
         * zooKeeper.getChildren(path, watch);
         * path：路径
         * watch：是否要启动监听，当子节点列表发生变化，会触发监听
         */
        List<String> children = zooKeeper.getChildren("/rxy-persistent", true);
        System.out.println(children);
    }
}
